package com.xy.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xy.webadmin.app.service.*;
import com.xy.webadmin.app.dao.*;
import com.xy.webadmin.app.model.*;
import com.xy.webadmin.upms.service.SysUserService;
import com.xy.webadmin.upms.service.SysDeptService;
import com.xy.common.core.base.dao.BaseDaoMapper;
import com.xy.common.core.constant.GlobalDeletedFlag;
import com.xy.common.core.object.Tuple2;
import com.xy.common.core.object.TokenData;
import com.xy.common.core.object.MyRelationParam;
import com.xy.common.core.object.CallResult;
import com.xy.common.core.base.service.BaseService;
import com.xy.common.core.util.MyModelUtil;
import com.xy.common.sequence.wrapper.IdGeneratorWrapper;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 家长数据操作服务类。
 *
 * @author xiaoyue
 * @date 2025-05-13
 */
@Slf4j
@Service("guardianService")
public class GuardianServiceImpl extends BaseService<Guardian, Long> implements GuardianService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private GuardianMapper guardianMapper;
    @Autowired
    private StudentGuardianMapper studentGuardianMapper;
    @Autowired
    private StudentGuardianService studentGuardianService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<Guardian> mapper() {
        return guardianMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Guardian saveNew(Guardian guardian) {
        guardianMapper.insert(this.buildDefaultValue(guardian));
        return guardian;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<Guardian> guardianList) {
        if (CollUtil.isNotEmpty(guardianList)) {
            guardianList.forEach(this::buildDefaultValue);
            guardianMapper.insertList(guardianList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<Guardian> guardianList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(guardianList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(guardianList.size(), start + batchSize);
            List<Guardian> subList = guardianList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<Guardian>, List<Guardian>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    guardianMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> guardianMapper.updateById(data));
            } else {
                guardianList.forEach(this::buildDefaultValue);
                guardianMapper.insertList(subList);
            }
            if (end == guardianList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(Guardian guardian, Guardian originalGuardian) {
        guardian.setCreateUserId(originalGuardian.getCreateUserId());
        guardian.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        guardian.setCreateTime(new Date());
        guardian.setUpdateTime(originalGuardian.getUpdateTime());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<Guardian> uw = this.createUpdateQueryForNullValue(guardian, guardian.getId());
        return guardianMapper.update(guardian, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        if (guardianMapper.deleteById(id) == 0) {
            return false;
        }
        // 开始删除多对多子表的关联
        StudentGuardian studentGuardian = new StudentGuardian();
        studentGuardian.setGuardianId(id);
        studentGuardianMapper.delete(new QueryWrapper<>(studentGuardian));
        // 开始删除多对多父表的关联
        return true;
    }

    @Override
    public List<Guardian> getGuardianList(Guardian filter, String orderBy) {
        return guardianMapper.getGuardianList(filter, orderBy);
    }

    @Override
    public List<Guardian> getGuardianListWithRelation(Guardian filter, String orderBy) {
        List<Guardian> resultList = guardianMapper.getGuardianList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public List<Guardian> getNotInGuardianListByStudentId(Long studentId, Guardian filter, String orderBy) {
        List<Guardian> resultList;
        if (studentId != null) {
            resultList = guardianMapper.getNotInGuardianListByStudentId(studentId, filter, orderBy);
        } else {
            resultList = getGuardianList(filter, orderBy);
        }
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        return resultList;
    }

    @Override
    public List<Guardian> getGuardianListByStudentId(
            Long studentId, Guardian filter, StudentGuardian studentGuardianFilter, String orderBy) {
        List<Guardian> resultList =
                guardianMapper.getGuardianListByStudentId(studentId, filter, studentGuardianFilter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForStudentGuardianList(resultList);
        return resultList;
    }

    @Override
    public Map<Long, List<Guardian>> getGuardianListMapByStudentList(
            List<Student> studentList, Guardian filter, String orderBy) {
        List<Long> studentIds = studentList.stream().map(Student::getId).collect(Collectors.toList());
        List<Guardian> resultList =
                guardianMapper.getGuardianListByStudentIds(studentIds, filter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForStudentGuardianList(resultList);
        return resultList.stream().collect(Collectors.groupingBy(s -> s.getStudentGuardian().getStudentId()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStudentGuardianList(List<StudentGuardian> studentGuardianList, Long guardianId) {
        TokenData tokenData = TokenData.takeFromRequest();
        for (StudentGuardian studentGuardian : studentGuardianList) {
            studentGuardian.setId(idGenerator.nextLongId());
            studentGuardian.setGuardianId(guardianId);
            studentGuardian.setCreateTime(new Date());
            studentGuardian.setCreateUserId(tokenData.getUserId());
            studentGuardian.setUpdateUserId(tokenData.getUserId());
            studentGuardianMapper.insert(studentGuardian);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStudentGuardian(StudentGuardian studentGuardian) {
        StudentGuardian filter = new StudentGuardian();
        filter.setGuardianId(studentGuardian.getGuardianId());
        filter.setStudentId(studentGuardian.getStudentId());
        StudentGuardian originalOne = studentGuardianMapper.selectOne(new QueryWrapper<>(filter));
        studentGuardian.setCreateTime(originalOne.getCreateTime());
        studentGuardian.setCreateTime(new Date());
        studentGuardian.setCreateUserId(originalOne.getCreateUserId());
        studentGuardian.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        UpdateWrapper<StudentGuardian> uw =
                BaseService.createUpdateQueryForNullValue(studentGuardian, StudentGuardian.class);
        uw.setEntity(filter);
        return studentGuardianMapper.update(studentGuardian, uw) > 0;
    }

    @Override
    public StudentGuardian getStudentGuardian(Long guardianId, Long studentId) {
        StudentGuardian filter = new StudentGuardian();
        filter.setGuardianId(guardianId);
        filter.setStudentId(studentId);
        return studentGuardianMapper.selectOne(new QueryWrapper<>(filter));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeStudentGuardian(Long guardianId, Long studentId) {
        StudentGuardian filter = new StudentGuardian();
        filter.setGuardianId(guardianId);
        filter.setStudentId(studentId);
        return studentGuardianMapper.delete(new QueryWrapper<>(filter)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeStudentGuardianList(Long guardianId, List<Long> studentIdList) {
        LambdaQueryWrapper<StudentGuardian> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentGuardian::getGuardianId, guardianId);
        queryWrapper.in(StudentGuardian::getStudentId, studentIdList);
        studentGuardianMapper.delete(queryWrapper);
    }

    @Override
    public CallResult verifyImportList(List<Guardian> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "companyId")) {
            callResult = verifyImportForDatasourceDict(dataList, "companyIdDictMap", Guardian::getCompanyId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "sysUserId")) {
            callResult = verifyImportForDatasourceDict(dataList, "sysUserIdDictMap", Guardian::getSysUserId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(Guardian guardian, Guardian originalGuardian) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(guardian, originalGuardian, Guardian::getCompanyId)
                && !sysDeptService.existId(guardian.getCompanyId())) {
            return CallResult.error(String.format(errorMessageFormat, "学校"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(guardian, originalGuardian, Guardian::getSysUserId)
                && !sysUserService.existId(guardian.getSysUserId())) {
            return CallResult.error(String.format(errorMessageFormat, "系统用户ID"));
        }
        return CallResult.ok();
    }

    private void buildRelationForStudentGuardianList(List<Guardian> resultList) {
        List<StudentGuardian> studentGuardianList =
                resultList.stream().map(Guardian::getStudentGuardian).collect(Collectors.toList());
        studentGuardianService.buildRelationForDataList(studentGuardianList, MyRelationParam.dictOnly());
    }

    private Guardian buildDefaultValue(Guardian guardian) {
        if (guardian.getId() == null) {
            guardian.setId(idGenerator.nextLongId());
        }
        TokenData tokenData = TokenData.takeFromRequest();
        guardian.setCreateUserId(tokenData.getUserId());
        guardian.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        guardian.setCreateTime(now);
        guardian.setUpdateTime(now);
        guardian.setIsDeleted(GlobalDeletedFlag.NORMAL);
        MyModelUtil.setDefaultValue(guardian, "openId", "");
        return guardian;
    }
}
